<?php

namespace Desktopd\MUA;


// EmailAddress (an email address with comment: eg. '"Foo" <foo@example.org>')
class EmailAddress {
    protected $label = false;
    protected $address;
    
    public function __construct ($address, $label = false) {
        $address = trim("$address");
        if (false === filter_var($address, FILTER_VALIDATE_EMAIL)) {
            throw new \DomainException("An invalid email address given (according to PHP's FILTER_VALIDATE_EMAIL)");
        }
        
        $this->address = $address;
        
        if ($label !== false && $label !== null && $label !== '') {
            $this->label = "$label";
        }
        
    }
    
    public function getAddress () {
        return $this->address;
    }
    
    public function __toString () {
        $address = $this->address;
        $label = $this->label;
        if ($label === false) {
            return $address;
        }
        
        // escape the label string!
        $original = $label;
        $label = (string) MIMEHeaderEncoding::encode($label);
        // defend against rewriting by MSA when possible
        //var_dump($original, $label);
        if ($original === $label && false === strpos($label, '"')) {
            $label = "\"{$label}\"";
        }
        
        return "$label <$address>";
    }
    
    public static function parse ($str, $exception = true) {
        $matches = array();
        if (preg_match('~^\s*(.+?)\s*<\s*(.+?)\s*>\s*$~', "$str", $matches)) {
            $label = (new MIMEHeaderEncoding(trim($matches[1])))->decode();
            $emailAddress = trim($matches[2]);
        } else {
            $label = false;
            $emailAddress = trim("$str");
        }
        
        if ($exception) {
            return new self($emailAddress, $label); // may throw a \DomainException
        }
        
        try {
            return new self($emailAddress, $label); // may throw a \DomainException
        } catch (\Exception $e) {
            return false;
        }
    }
}


// vim: ts=4 et ai

